package cn.tedu.ivos.service.template;
import java.util.concurrent.TimeUnit;
import cn.tedu.ivos.base.constant.CacheConstants;
import cn.tedu.ivos.base.security.context.AuthenticationContextHolder;
import cn.tedu.ivos.base.utils.SecurityUtils;
import cn.tedu.ivos.base.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;


@Component
public class PasswordTemplate
{
    @Autowired
    private CacheTemplate redisService;
    private int maxRetryCount = CacheConstants.PASSWORD_MAX_RETRY_COUNT;
    private Long lockTime = CacheConstants.PASSWORD_LOCK_TIME;

    /**
     * 登录账户密码错误次数缓存键名
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username)
    {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    public void validate(String dbPassword)
    {
        Authentication authentication =
                AuthenticationContextHolder.getContext();
        String username = authentication.getName();
        String inputPassword = authentication.getCredentials().toString();
        Integer retryCount = redisService.getCacheObject(getCacheKey(username));
        if (retryCount == null) {
            retryCount = 0;
        }

        if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
            String errMsg = String.format("密码输入错误%s次，帐户锁定%s分钟", maxRetryCount, lockTime);
            throw new ServiceException(errMsg);
        }

        if (!matches(dbPassword, inputPassword)) {
            retryCount = retryCount + 1;
            redisService.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new ServiceException("用户不存在/密码错误");
        }
        else {
            clearLoginRecordCache(username);
        }
    }

    public boolean matches(String dbPassword, String rawPassword) {
        return SecurityUtils.matchesPassword(rawPassword, dbPassword);
    }

    public void clearLoginRecordCache(String loginName) {
        if (redisService.hasKey(getCacheKey(loginName)))
        {
            redisService.deleteObject(getCacheKey(loginName));
        }
    }
}
